#include<Ticker.h>
#include <SoftwareSerial.h>
Ticker flipper;
int sensorValue = 0;
int Pulse_number = 0;
int rotate = 0;
int pwm = 0;
int rotate_set = 0;

void motor_rotate(){
  rotate = Pulse_number*10*60/426;
  Pulse_number = 0;
  Serial.print("当前转速为：");
  Serial.println(rotate);
  Serial.print("设定转速为：");
  Serial.println(rotate_set);
  Serial.print("此时pwm输出为：");
  Serial.println(pwm);
}

//反馈脉冲中断计算
ICACHE_RAM_ATTR void InterruptFunc(){   //中断响应函数
  Pulse_number ++;
}


//按键中断，增加设定转速
ICACHE_RAM_ATTR void PRRESS_KEY(){ 
  if(rotate_set == 0){
    rotate_set = 80; 
  }else if(rotate_set<120){
    rotate_set = rotate_set+10;
  }else{
    rotate_set = 126;
  }
}


//按键中断，减少设定转速
ICACHE_RAM_ATTR void PRRESS_KEY_decrease(){
  if(rotate_set == 126){
      rotate_set = 120; 
    }else if(rotate_set <= 80){
      rotate_set = 0;
    }else{
      rotate_set = rotate_set - 10;
    }  
}


void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(12,OUTPUT);       //pwm控制电机
  digitalWrite(4,HIGH);     //控制正反转
  digitalWrite(5,LOW);
  //pinMode(3, INPUT_PULLUP); //按键通道
  //pinMode(14, INPUT_PULLUP); //按键通道
  pinMode(10, INPUT_PULLUP);  //脉冲通道
  attachInterrupt(digitalPinToInterrupt(10), InterruptFunc, RISING);  //脉冲反馈
  attachInterrupt(digitalPinToInterrupt(2), PRRESS_KEY, RISING);   //增加转速
  attachInterrupt(digitalPinToInterrupt(14), PRRESS_KEY_decrease, RISING);  //减速转速
  
  digitalWrite(12,0); //
  flipper.attach(0.1,motor_rotate);  //0.1s计算一次脉冲
}

void loop() {
    //sensorValue = analogRead(16);
    //Serial.println(sensorValue);
   PID_Concrol();
   analogWrite(12,pwm);
   delay(3);  
}

float kp = 3;
float ki = 0.1;
float kd = 0.2;
int error = 0;
int error_last = 0;
int error_last2 = 0;
int umax = 129;
int umin = -129;
int integral = 0;
float pwm1 = 0 ;
void PID_Concrol(){
  error = rotate_set - rotate;
  pwm1 = pwm1+kp*(error-error_last)+ki*error+kd*(error-2*error_last+error_last2);
  error_last2 = error_last;
  error_last = error;
  if(pwm1>1023){
    pwm1 = 1023;
  }
  if(pwm1<0){
    pwm1 = 0;
  }
  pwm = int(pwm1);
}
